package com.yex.service;

import com.yex.base.Constant;
import com.yex.common.exception.RRException;
import com.yex.common.utils.DateUtil;
import com.yex.common.utils.PageUtils;
import com.yex.entity.*;
import com.yex.util.CommonModifyUtil;
import com.yex.utils.FileUtil;
import com.yex.utils.JsonResultVo;
import com.yex.utils.Utils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author Little Liu
 * @version V1
 * @date Created in 2018/12/26 9:10
 * @description 描述
 */
@Service
public class ApiService {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private BankService bankService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private LocaleMessageSourceService message;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private BankListService bankListService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private NoticeUserService noticeUserService;
    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private InvestmentOrderService investmentOrderService;
    @Autowired
    private InvestmentService investmentService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private InvestService investService;

    @Autowired
    private WalletLogService walletLogService;
    @Autowired
    private InvestLogService investLogService;
    @Autowired
    private IntegralLogService integralLogService;
    @Autowired
    private InvestmentLogService investmentLogService;

    /**
     * 注册
     *
     * @param request
     * @return
     */
    public JsonResultVo register(HttpServletRequest request) {
        String mobile = request.getParameter("mobile");
        String introMobile = request.getParameter("introMobile");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        String area = request.getParameter("area");
        area = StringUtils.isBlank(area) ? "86" : area;

        String ip = Utils.getIpAddr(request);
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(password) || StringUtils.isBlank(code)) {
            throw new RRException("缺少必填参数");
        }

        if (!mobile.matches("^\\d{10,14}$")) {
            throw new RRException("手机号码格式错误");
        }

        UserEntity userEntity = userService.selectUserByMobile(mobile);
        if (userEntity != null) {
            throw new RRException("手机号已注册");
        }
        Integer introUserid = null;
        if (!StringUtils.isBlank(introMobile)) {
            userEntity = userService.selectUserByMobileOrUid(introMobile);
            if (userEntity == null) {
                throw new RRException("推荐人不存在或已被删除");
            }
            introUserid = userEntity.getId();
        }

        boolean verifyCode = verifyCode(mobile, code, Constant.smgCodeType_1);
        if (!verifyCode) {
            return new JsonResultVo(message.getMessage("code_error"), -1);
        }

        return userService.insertUser(mobile, area, introUserid, password, ip);
    }

    /**
     * 登录
     *
     * @param request
     * @return
     */
    public JsonResultVo login(HttpServletRequest request) {
        String mobile = request.getParameter("mobile");
        String password = request.getParameter("password");
        String ip = Utils.getIpAddr(request);
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(password)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }
        return userService.updateUserByLogin(mobile, password, ip);
    }

    /**
     * 设置交易密码
     *
     * @param request
     * @return
     */
    public JsonResultVo setMoneyPassword(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        String password = request.getParameter("password");
        if (StringUtils.isBlank(password)) {
            throw new RRException("请输入支付密码");
        }

        if (password.length() != 6) {
            throw new RRException("支付密码必须为6位");
        }

        if (userEntity.getMoneyPassword() != null) {
            throw new RRException("该用户已经设置了支付密码,请勿重复设置");
        }

        return userService.updateMoneyPassword(userEntity, password);
    }

    /**
     * 忘记密码
     *
     * @param request
     * @return
     */
    public JsonResultVo forgetPassword(HttpServletRequest request) {
        String mobile = request.getParameter("mobile");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(password) || StringUtils.isBlank(repassword)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (!password.equals(repassword)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        return userService.updateForgetPassword(mobile, password);
    }

    /**
     * 修改密码
     *
     * @param request
     * @return
     */
    public JsonResultVo modifyPassword(HttpServletRequest request) {
        String oldPassword = request.getParameter("oldPassword");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String code = request.getParameter("code");
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(password) || StringUtils.isBlank(repassword) || StringUtils.isBlank(code)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (!password.equals(repassword)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (!userEntity.getPassword().equals(DigestUtils.sha256Hex(oldPassword))) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        boolean verifyCode = verifyCode(userEntity.getMobile(), code, Constant.smgCodeType_3);
        if (!verifyCode) {
            return new JsonResultVo(message.getMessage("code_error"), -1);
        }

        return userService.updateModifyPassword(userEntity, password);
    }

    /**
     * 修改交易密码
     *
     * @param request
     * @return
     */
    public JsonResultVo modifyMoneyPassword(HttpServletRequest request) {
        String oldPassword = request.getParameter("oldPassword");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String code = request.getParameter("code");
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(password) || StringUtils.isBlank(repassword) || StringUtils.isBlank(code)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (!password.equals(repassword)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (password.length() != 6) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (!userEntity.getMoneyPassword().equals(DigestUtils.sha256Hex(oldPassword))) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        boolean verifyCode = verifyCode(userEntity.getMobile(), code, Constant.smgCodeType_4);
        if (!verifyCode) {
            return new JsonResultVo(message.getMessage("code_error"), -1);
        }

        return userService.updateMoneyPassword(userEntity, password);
    }

    private boolean verifyCode(String mobile, String code, String type) {
        MessageEntity messageEntity = messageService.selectMessageSend(mobile, code, type);
        if (messageEntity == null) {
            return false;
        }
        Integer verify = messageService.updateMessageVerify(messageEntity.getId());

        if (verify <= 0) {
            return false;
        }
        return true;
    }

    public UserEntity verifyToken(String token) {
        if (StringUtils.isBlank(token)) {
            HttpServletRequest request = CommonModifyUtil.getRequest();
            token = request.getHeader("token");
            if (StringUtils.isBlank(token)) {
                token = request.getParameter("token");
                if (StringUtils.isBlank(token)) throw new RRException("not_login");
            }
        }
        TokenEntity tokenEntity = tokenService.queryByToken(token);
        if (tokenEntity == null) {
            return null;
        }

        if (tokenEntity.getExpireTime().getTime() - System.currentTimeMillis() < 0) {
            return null;
        }

        UserEntity userEntity = userService.selectById(tokenEntity.getUserId());
        if (userEntity == null) {
            return null;
        }

        return userEntity;
    }

    /**
     * 重置交易密码
     *
     * @param request
     * @return
     */
    public JsonResultVo resetMoneyPassword(HttpServletRequest request) {
        String loginPassword = request.getParameter("loginPassword");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String code = request.getParameter("code");
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        if (StringUtils.isBlank(loginPassword) || StringUtils.isBlank(password) || StringUtils.isBlank(repassword) || StringUtils.isBlank(code)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (!password.equals(repassword)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (password.length() != 6) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (!userEntity.getPassword().equals(DigestUtils.sha256Hex(loginPassword))) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        boolean verifyCode = verifyCode(userEntity.getMobile(), code, Constant.smgCodeType_5);
        if (!verifyCode) {
            return new JsonResultVo(message.getMessage("code_error"), -1);
        }

        return userService.updateMoneyPassword(userEntity, password);
    }

    /**
     * 发送短信
     *
     * @param request
     * @return
     */
    public JsonResultVo sendSmg(HttpServletRequest request) {
        String type = request.getParameter("type");
        String mobile = request.getParameter("mobile");
        if (StringUtils.isBlank(type) || StringUtils.isBlank(mobile)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        MessageEntity messageEntity = messageService.selectMessageSendTime(mobile, type);
        if (messageEntity != null) {
            long start = System.currentTimeMillis();
            long end = messageEntity.getCreateTime().getTime();
            long time = 60 * 1000;
            if (start - end < time) {
                return new JsonResultVo(message.getMessage("fail"), -1);
            }
        }

        //注册
        if (type.equals(Constant.smgCodeType_1)) {
            UserEntity userEntity = userService.selectUserByMobile(mobile);
            if (userEntity != null) {
                return new JsonResultVo(message.getMessage("mobile_has_register"), -1);
            }
            Integer messageId = messageService.insertMessage(mobile, Constant.smgCodeTemplateId, Utils.randomInteger(4), type, null);
            if (messageId == 0) {
                return new JsonResultVo(message.getMessage("fail"), -1);
            }
            messageService.sendMessage(messageId);
            return new JsonResultVo(message.getMessage("success"));
        } else if (type.equals(Constant.smgCodeType_2) || type.equals(Constant.smgCodeType_3) || type.equals(Constant.smgCodeType_4) || type.equals(Constant.smgCodeType_5)) {
            UserEntity userEntity = userService.selectUserByMobile(mobile);
            if (userEntity == null) {
                return new JsonResultVo(message.getMessage("mobile_not_exist"), -1);
            }
            Integer messageId = messageService.insertMessage(mobile, Constant.smgCodeTemplateId, Utils.randomInteger(4), type, userEntity);
            messageService.sendMessage(messageId);
            return new JsonResultVo(message.getMessage("success"));
        }
        return new JsonResultVo(message.getMessage("parameter_error"), -1);
    }

    /**
     * 直推用户
     *
     * @param request
     * @return
     */
    public JsonResultVo userIntroList(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        return userService.selectIntroList(userEntity.getId());
    }

    /**
     * 用户信息
     *
     * @param request
     * @return
     */
    public JsonResultVo userInfo(HttpServletRequest request) {

        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        return userService.userInfo(userEntity);
    }

    /**
     * 上传头像
     *
     * @param request
     * @return
     */
    public JsonResultVo uploadUserPhoto(HttpServletRequest request) {

        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        try {
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = mRequest.getFile("file");
            InputStream inputStream = multipartFile.getInputStream();
            String realName = multipartFile.getOriginalFilename();
            if (StringUtils.isBlank(realName)) {
                return new JsonResultVo(message.getMessage("img_format_error"), -1);
            }

            String[] nameSplit = realName.split("\\.");
            String ext = nameSplit[nameSplit.length - 1];
            if (ext != null && !ext.trim().toLowerCase().endsWith("jpg")
                    && !ext.trim().toLowerCase().endsWith("bmp")
                    && !ext.trim().toLowerCase().endsWith("png") && !ext.trim().toLowerCase().endsWith("jpeg")) {
                return new JsonResultVo(message.getMessage("img_format_error"), -1);
            }

            String realPath = Constant.uploadPicPath + Constant.uploadPicDirectory;
            String fileName = Utils.getRandomImageName() + "." + ext;
            boolean b = FileUtil.savePhotoFile(realPath, fileName, inputStream, Constant.uploadPicDirectory);
            Map<String, Object> map = new HashMap<>(1);
            if (b) {
                Integer ret = userService.updateUserPhoto(Constant.uploadPicDirectory + "/" + fileName, userEntity.getId());
                if (ret > 0) {
                    map.put("fileName", Constant.uploadPicDirectory + "/" + fileName);
                    return new JsonResultVo(message.getMessage("success"), map, 0);
                }
            }
            return new JsonResultVo(message.getMessage("fail"), -1);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResultVo(message.getMessage("fail"), -1);
        }

    }

    /**
     * 实名认证
     *
     * @param request
     * @return
     */
    public JsonResultVo realNameAuth(HttpServletRequest request) {

        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }


        if (userEntity.getRealValidate() == 1) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        String type = request.getParameter("type");
        String name = request.getParameter("realName");
        String identityNumber = request.getParameter("identityNumber");
        if (StringUtils.isBlank(type) || StringUtils.isBlank(name) || StringUtils.isBlank(identityNumber)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        List<UserEntity> userByIdentityNumber = userService.selectUserByIdentityNumber(identityNumber);

        if (userByIdentityNumber.size() > 3) {
            return new JsonResultVo(message.getMessage("identity_there"), -1);
        }

        userEntity.setRealName(name);
        userEntity.setIdentityNumber(identityNumber);
        userEntity.setRealValidate(1);
        if ("1".equals(type)) {
            userEntity.setIdentityType(1);
            return userService.updateRealNameAuth(userEntity);
        } else if ("2".equals(type)) {
            try {
                MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
                MultipartFile multipartFile = mRequest.getFile("file");
                InputStream inputStream = multipartFile.getInputStream();
                String realName = multipartFile.getOriginalFilename();
                if (StringUtils.isBlank(realName)) {
                    return new JsonResultVo(message.getMessage("img_format_error"), -1);
                }
                String[] nameSplit = realName.split("\\.");
                String ext = nameSplit[nameSplit.length - 1];
                if (ext != null && !ext.trim().toLowerCase().endsWith("jpg")
                        && !ext.trim().toLowerCase().endsWith("bmp")
                        && !ext.trim().toLowerCase().endsWith("png") && !ext.trim().toLowerCase().endsWith("jpeg")) {
                    return new JsonResultVo(message.getMessage("img_format_error"), -1);
                }
                String realPath = Constant.uploadPicPath + Constant.uploadPicDirectory;
                String fileName = Utils.getRandomImageName() + "." + ext;
                boolean b = FileUtil.savePhotoFile(realPath, fileName, inputStream, Constant.uploadPicDirectory);
                if (b) {
                    userEntity.setIdentityType(2);
                    userEntity.setIdentityPath(Constant.uploadPicDirectory + "/" + fileName);
                    return userService.updateRealNameAuth(userEntity);
                }

                return new JsonResultVo(message.getMessage("fail"), -1);
            } catch (Exception e) {
                e.printStackTrace();
                return new JsonResultVo(message.getMessage("fail"), -1);
            }
        }
        return new JsonResultVo(message.getMessage("parameter_error"), -1);
    }

    public JsonResultVo addBank(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        String name = request.getParameter("name");
        String cardNumber = request.getParameter("cardNumber");
        String address = request.getParameter("address");
        String branchAddress = request.getParameter("branchAddress");
        String bank = request.getParameter("bank");

        if (StringUtils.isBlank(cardNumber) || StringUtils.isBlank(name) || StringUtils.isBlank(address) || StringUtils.isBlank(branchAddress) || StringUtils.isBlank(bank)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        BankListEntity bankListEntity = bankListService.selectById(bank);
        if (bankListEntity == null) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        BankEntity bankEntity = new BankEntity();
        bankEntity.setUserId(userEntity.getId());
        bankEntity.setName(name);
        bankEntity.setCardNumber(cardNumber);
        bankEntity.setAddress(address);
        bankEntity.setBranchAddress(branchAddress);
        bankEntity.setBank(Integer.valueOf(bank));
        bankEntity.setCreateTime(new Date());
        bankEntity.setUpdateTime(new Date());
        bankEntity.setStatus(1);

        return bankService.insertBank(bankEntity);
    }

    public JsonResultVo deleteBank(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        String id = request.getParameter("id");
        if (StringUtils.isBlank(id)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        return bankService.deleteBank(id, userEntity.getId());
    }


    public JsonResultVo userBank(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        return bankService.selectBankByUserId(userEntity.getId());
    }


    public JsonResultVo addOrder(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        String type = request.getParameter("type");
        String price = request.getParameter("price");
        String number = request.getParameter("number");

        if (StringUtils.isBlank(type) || StringUtils.isBlank(price) || StringUtils.isBlank(number)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUserId(userEntity.getId());
        orderEntity.setType(Integer.valueOf(type));
        orderEntity.setPrice(new BigDecimal(price));
        orderEntity.setNumber(new BigDecimal(number));
        orderEntity.setStatus(0);
        orderEntity.setCreateTime(new Date());
        orderEntity.setUpdateTime(new Date());

        return orderService.insertOrder(orderEntity);
    }


    public JsonResultVo payOrder(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        String orderId = request.getParameter("orderId");

        if (StringUtils.isBlank(orderId)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        return orderService.updatePayOrder(orderId);

    }

    public JsonResultVo revokeOrder(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        String orderId = request.getParameter("orderId");
        if (StringUtils.isBlank(orderId)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        return orderService.updateRevokeOrder(orderId);
    }

    public JsonResultVo orderInfo(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        String orderId = request.getParameter("orderId");
        return orderService.selectOrderInfo(userEntity.getId(), orderId);
    }

    public JsonResultVo orderList(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        String type = request.getParameter("type");
        String status = request.getParameter("status");
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");

        Map<String, Object> params = new HashMap<>(2);
        params.put("page", page == null ? 1 : page);
        params.put("limit", limit == null ? 10 : limit);

        StringBuilder filter = new StringBuilder(" where 1=1 and o.user_id=" + userEntity.getId());
        if (!StringUtils.isBlank(type)) {
            filter.append(" and o.type=" + type);
        }

        if (!StringUtils.isBlank(status)) {
            if ("3".equals(status)) {
                filter.append(" and o.status in (3,4) ");
            } else {
                filter.append(" and o.status=" + status);
            }
        }

        filter.append(" order by o.id desc");

        PageUtils pageList = orderService.queryPage(params, filter.toString());

        return new JsonResultVo(message.getMessage("success"), pageList, 0);
    }

    /**
     * 钱包互转
     *
     * @param request
     * @return
     */
    public JsonResultVo transferWallet(HttpServletRequest request) {
        String token = request.getParameter("token");
        String mobile = request.getParameter("mobile");
        String number = request.getParameter("number");
        UserEntity userEntity = verifyToken(token);

        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(number)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (userEntity.getMobile().equals(mobile)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        return walletService.updateTransferWallet(mobile, number, userEntity.getId());
    }

    public JsonResultVo buyInvest(HttpServletRequest request) {
        String token = request.getParameter("token");
        String number = request.getParameter("number");
        UserEntity userEntity = verifyToken(token);

        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        if (StringUtils.isBlank(number)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        return investService.updateBuyInvest(number, userEntity.getId());
    }

    /**
     * 钱包排单币
     *
     * @param request
     * @return
     */
    public JsonResultVo transferInvest(HttpServletRequest request) {
        String token = request.getParameter("token");
        String mobile = request.getParameter("mobile");
        String number = request.getParameter("number");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(number)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (userEntity.getMobile().equals(mobile)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        return investService.updateTransferInvest(mobile, number, userEntity.getId());
    }

    /**
     * 添加问题
     *
     * @param request
     * @return
     */
    public JsonResultVo question(HttpServletRequest request) {
        String token = request.getParameter("token");
        String content = request.getParameter("content");
        UserEntity userEntity = verifyToken(token);

        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        if (StringUtils.isBlank(content)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }
        String ip = Utils.getIpAddr(request);
        return questionService.insertQuestion(userEntity.getId(), content, ip);
    }

    /**
     * 问题列表
     *
     * @param request
     * @return
     */
    public JsonResultVo questionList(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);

        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        return questionService.selectQuestionList(userEntity.getId());
    }

    public JsonResultVo bankList(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }

        return bankListService.selectBankList();
    }

    /**
     * 公告列表
     *
     * @param request
     * @return
     */

    public JsonResultVo noticeList(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        return noticeService.selectNoticeList(userEntity.getId());
    }

    /**
     * 读取公告
     *
     * @param request
     * @return
     */
    public JsonResultVo readNotice(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        String noticeId = request.getParameter("noticeId");

        if (StringUtils.isBlank(noticeId)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        NoticeEntity noticeEntity = noticeService.selectById(noticeId);
        if (noticeEntity == null) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        return noticeUserService.insertNoticeUser(noticeId, userEntity.getId());
    }


    public JsonResultVo verifySmg(HttpServletRequest request) {
        String code = request.getParameter("code");
        String mobile = request.getParameter("mobile");
        String type = request.getParameter("type");
        boolean verifyCode = verifyCode(mobile, code, type);
        if (!verifyCode) {
            return new JsonResultVo(message.getMessage("code_error"), -1);
        }
        return new JsonResultVo(message.getMessage("success"));
    }

    public JsonResultVo orderConfigure(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("buyPrice", sysConfigService.getValue("buyPrice"));
        map.put("sellPrice", sysConfigService.getValue("sellPrice"));
        return new JsonResultVo(message.getMessage("success"), map, 0);
    }

    /**
     * 报单
     *
     * @param request
     * @return
     */
    public JsonResultVo addInvestmentOrder(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        String investmentId = request.getParameter("investmentId");
        String number = request.getParameter("number");

        if (StringUtils.isBlank(investmentId) || StringUtils.isBlank(number)) {
//            return new JsonResultVo(message.getMessage("parameter_error"), -1);
            throw new RRException("缺少必填参数");
        }

        if (Integer.valueOf(number) < Constant.ONE_THOUSAND) {
//            return new JsonResultVo(message.getMessage("parameter_error"), -1);
            throw new RRException("余额数量必须大于1000");
        }

        if (Integer.valueOf(number) % Constant.ONE_THOUSAND != 0) {
//            return new JsonResultVo(message.getMessage("parameter_error"), -1);
            throw new RRException("余额数量必须为1000的整数倍");
        }

        return investmentOrderService.insertInvestmentOrder(investmentId, number, userEntity.getId());
    }

    /**
     * 复投报单
     *
     * @param request
     * @return
     */
    public JsonResultVo replyInvestmentOrder(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        String investmentOrderId = request.getParameter("investmentOrderId");
        String number = request.getParameter("number");

        if (StringUtils.isBlank(investmentOrderId) || StringUtils.isBlank(number)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (Integer.valueOf(number) < Constant.ONE_THOUSAND) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        if (Integer.valueOf(number) % Constant.ONE_THOUSAND != 0) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }

        return investmentOrderService.updateInvestmentOrder(investmentOrderId, number, userEntity.getId());
    }

    /**
     * 赎回报单
     *
     * @param request
     * @return
     */
    public JsonResultVo redeemInvestmentOrder(HttpServletRequest request) {

        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        String investmentOrderId = request.getParameter("investmentOrderId");
        String type = request.getParameter("type");

        if (StringUtils.isBlank(investmentOrderId) || StringUtils.isBlank(type)) {
            return new JsonResultVo(message.getMessage("parameter_error"), -1);
        }


        return investmentOrderService.updateRedeemInvestmentOrder(investmentOrderId, type, userEntity.getId());
    }

    /**
     * 报单产品
     *
     * @param request
     * @return
     */
    public JsonResultVo investment(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        InvestmentEntity investmentEntity = investmentService.selectByOne();
        Map<String, Object> map = new HashMap<>(5);
        if (investmentEntity != null) {
            long days = DateUtil.spaceDays(investmentEntity.getEndTime(), investmentEntity.getStartTime());
            map.put("id", investmentEntity.getId());
            map.put("profit", investmentEntity.getProfit());
            map.put("day", days);
        } else {
            map.put("id", 0);
            map.put("profit", 0);
            map.put("day", 0);
        }
        return new JsonResultVo(message.getMessage("success"), map, 0);
    }

    /**
     * 历史报单
     *
     * @param request
     * @return
     */
    public JsonResultVo investmentOrderList(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        return investmentOrderService.selectInvestmentOrderByUserId(userEntity.getId());
    }

    /**
     * 钱包日志
     *
     * @param request
     * @return
     */
    public JsonResultVo consumptionRecord(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("user_id", userEntity.getId());
        List<WalletLogEntity> walletLogList = walletLogService.selectByMap(map);
        List<InvestLogEntity> investLogList = investLogService.selectByMap(map);
        List<IntegralLogEntity> integralLogList = integralLogService.selectByMap(map);
        Map<String, Object> mapList = new HashMap<>(2);
        mapList.put("walletLog", walletLogList);
        mapList.put("investLog", investLogList);
        mapList.put("integralLog", integralLogList);
        return new JsonResultVo(message.getMessage("success"), mapList, 0);
    }

    /**
     * 奖励
     *
     * @param request
     * @return
     */
    public JsonResultVo userInvestment(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        return investmentService.selectUserInvestment(userEntity.getId());
    }

    /**
     * 本期报单
     *
     * @param request
     * @return
     */
    public JsonResultVo userInvestmentOrder(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        return investmentOrderService.selectUserInvestmentOrder(userEntity.getId());
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    public JsonResultVo signOut(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        tokenService.expireToken(userEntity.getId());
        return new JsonResultVo(message.getMessage("success"));
    }

    /**
     * 退出系统
     *
     * @param request
     * @return
     */
    public JsonResultVo signOutSystem(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        tokenService.expireToken(userEntity.getId());
        userEntity.setStatus(2);
        userEntity.setMobile(userEntity.getMobile() + DateUtil.getCurrTime());
        userService.updateById(userEntity);
        return new JsonResultVo(message.getMessage("success"));
    }

    /**
     * 团队管理
     *
     * @param request
     * @return
     */
    public JsonResultVo teamManage(HttpServletRequest request) {
        String token = request.getParameter("token");
        UserEntity userEntity = verifyToken(token);
        if (userEntity == null) {
            return new JsonResultVo(message.getMessage("not_login"), -1001);
        }
        List<Map<String, Object>> mapList = new ArrayList<>(10);
        Map<String, Object> map = new HashMap<>(2);
        map.put("name", "直推人数");
        map.put("val", userEntity.getIntroUserCount());
        mapList.add(map);

        map = new HashMap<>(2);
        map.put("name", "伞下人数");
        map.put("val", userEntity.getIntroDownCount());
        mapList.add(map);

        map = new HashMap<>(2);
        map.put("name", "直推业绩");
        map.put("val", investmentLogService.selectIntroUserTotal(userEntity.getId()));
        mapList.add(map);

        return new JsonResultVo(message.getMessage("success"), mapList, 0);
    }
}
